import { NORMAL_CODE } from '@/constants';
import { Cascader } from 'antd';
import { useEffect, useState } from 'react';

const ICascader: React.FC = (props) => {
  const valueConfig = {
    api: props.valueConfig.api,
    field: props.valueConfig.field,
    value_key: props.value_key ? props.value_key : 'id',
    name_key: props.name_key ? props.name_key : 'name',
  };
  const [value, setValue] = useState(() => {
    return props.value instanceof Array
      ? props.value.map((item) => (isNaN(parseInt(item)) ? 0 : parseInt(item)))
      : [];
  });
  const [treeData, setTreeData] = useState([]);

  const custom_request = async (id) => {
    const param = {
      search_page: 1,
      search_limit: 0,
    };
    param[valueConfig.field] = id;
    const res = await valueConfig.api(param);
    if (res.code !== NORMAL_CODE) {
      return [];
    }
    return res.data.list;
  };

  useEffect(() => {
    const asyncFn = async () => {
      const treeRequest = async (index) => {
        let id = 0;
        if (index > 0) {
          id = value[index - 1];
        }
        let data = await custom_request(id);
        data = data.map(async (item) => {
          const new_Item = {
            label: item[valueConfig.name_key],
            value: item[valueConfig.value_key],
            isLeaf: false,
          };
          if (item[valueConfig.value_key] == value[index] && index < value.length - 1) {
            new_Item.children = await treeRequest(index + 1);
          }
          return new_Item;
        });
        data = await Promise.all(data);
        return data;
      };
      //组装数据
      const data = await treeRequest(0);
      setTreeData(data);
    };
    asyncFn();
  }, []);

  const onChange = (value, selectedOptions) => {
    props.onChange(value);
  };

  const loadData = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const list = await custom_request(targetOption.value);
    const data = list.map((item) => {
      const new_Item = {
        label: item[valueConfig.name_key],
        value: item[valueConfig.value_key],
      };
      if (selectedOptions.length < value.length - 1) {
        new_Item.isLeaf = false;
      }
      return new_Item;
    });
    targetOption.children = data;
    targetOption.loading = false;
    setTreeData([...treeData]);
  };

  return (
    <Cascader
      defaultValue={value}
      options={treeData}
      loadData={loadData}
      onChange={onChange}
      changeOnSelect
    />
  );
};

export default ICascader;
